<?php
namespace Home\Controller;
use Payment\Common\PayException;
use Payment\Client\Charge;
use Payment\Config;
use plugins\payment\wechat\WechatSubmit;

class OrderController extends HomeController
{
    public function __construct()
    {
        parent::__construct(); 
    }

    public function index()
    {
        $this->display();
    }
    //商品列表
    public function goods(){
//        $load=I('load') ? I('load') : 1;
        //$url = '';
        if( I('type') ){
            $where['type'] = I('type');
            //$url .= ""
        }
        if( I('cost') ){
            $where['cost'] = I('cost');
        }elseif (I('cost')==='0'){
            $where['cost'] = I('cost');
        }
        if( I('time') ){
            $time= I('time');
            $a=strtotime(date('Y-m-d',time()));
            if($time==='1'){
                $where['start_time'] = ['GT',$a];
            }else{
              $a= $a-86400*$time;
              $where['start_time'] = ['GT',$a];
            }
        } 
        $where['status'] = 1;

        $User=M('active');
        $activeList=$User->where($where)->order('create_time')->select();
        foreach ($activeList as $k => $v) {
            $v["order_count"] = M("order")->where(["active_id"=>$v["id"]])->count();
            $activeList[$k] = $v;
        }

        $this->assign('activeList',$activeList);
        $this->display();
    }

    /**
     * 商品详情页
     */

    public function details()
    {
        $where['id'] = I('pid');
        $User=M('active');
        $activeList=$User->where($where)->order('create_time')->select();

        $count=M("order")->where(["active_id"=>I('pid')])->count();

        //检查是否收藏
        $b['active_id'] = I('pid');
        $b['user_id'] = UID;
        $Coll=M('collection');

        if($Coll->where($b)->select()){
            $collection='1';
        }else{
            $collection='0';
        }

        $this->assign('activeList',$activeList); 
        $this->assign('count',$count);
        $this->assign('collection',$collection);


        $UserList = M()
            ->field('a.id,b.nickname,b.headimgurl')
            ->table('jt_order as a')
            ->join ('jt_member as b on a.`user_id` = b.`uid`')
            ->where("a.`active_id`=".I('pid'))
            ->group('b.uid')
            ->select();
        //var_dump($UserList);
        $this->assign('UserList',$UserList);

        $this->display();
    }


    /**
     * 下单页
     */
    public function confirm()
    { 
        $openid=$this->GetOpenid(); 
        $this->assign('openid',$openid);
        $this->display();
    }

    public function confirm_msg()
    {
        $id = I('id');
        $Order = M("active");
        $a=$Order->where('id='.$id)->find();
        $this->assign('active',$a);
        $this->display();
    } 

    public  function  alipay(){
        require_once("plugins/payment/alipayMobile/alipay.config.php");
        include_once  "plugins/payment/alipayMobile/lib/alipay_submit.class.php"; 
        $orderNo = I('sn');

        $Order = M("order");
        $a=$Order->where('order_sn='.$orderNo)->find();
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $orderNo;
        //订单名称，必填
        $subject = '优才圈商城';
        //付款金额，必填
        $total_fee = $a['active_price'];
        //收银台页面上，商品展示的超链接，必填
        $show_url = "http://".$_SERVER["SERVER_NAME"];

        //商品描述，可空
        $body = '';
        /************************************************************/ 
        //构造要请求的参数数组，无需改动
        $parameter = array(
                "service"       => $alipay_config['service'],
                "partner"       => $alipay_config['partner'],
                "seller_id"  => $alipay_config['seller_id'],
                "payment_type"  => $alipay_config['payment_type'],
                "notify_url"    => $alipay_config['notify_url'],
                "return_url"    => $alipay_config['return_url'],
                "_input_charset"    => trim(strtolower($alipay_config['input_charset'])),
                "out_trade_no"  => $out_trade_no,
                "subject"   => $subject,
                "total_fee" => $total_fee,
                "show_url"  => $show_url,
                "body"  => $body,
                //其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.2Z6TSk&treeId=60&articleId=103693&docType=1
                //如"参数名"    => "参数值"   注：上一个参数末尾需要“,”逗号。
                
        );
        //建立请求
        $alipaySubmit = new \AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
        echo $html_text; 

        // date_default_timezone_set('Asia/Shanghai');
        // $aliConfig = C('ALIPAY_CONFIG');  
        // // 订单信息
        // $orderNo = I('sn');

        // $Order = M("order");
        // $a=$Order->where('order_sn='.$orderNo)->find();
        // // var_dump($a['active_price']);exit;
        // $payData = [
        //     'body'    => 'ali wap pay',
        //     'subject'    => '测试支付宝手机网站支付',
        //     'order_no'    => $orderNo.'A'.time(),
        //     'timeout_express' => time() + 600,// 表示必须 600s 内付款
        //     'amount'    => $a['active_price'],// 单位为元 ,最小为0.01
        //     'return_param' => 'tata',// 一定不要传入汉字，只能是 字母 数字组合
        //     // 'client_ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1',// 客户地址
        //     'goods_type' => '1',// 0—虚拟类商品，1—实物类商品
        //     'store_id' => '',
        //     'quit_url' => $_SERVER["SERVER_NAME"], // 收银台的返回按钮（用户打断支付操作时返回的地址,4.0.3版本新增）
        // ];
        // try {
        //     $url = Charge::run(Config::ALI_CHANNEL_WAP, $aliConfig, $payData);
        // } catch (PayException $e) {
        //     echo $e->errorMessage();
        //     exit;
        // }
        // header('Location:' . $url);
    }
    /**
     * 支付方法
     */
    public function payOrder(){ 
        $trade_status=I('trade_status');
        $out_trade_no = I('out_trade_no');
        $trade_no = I('trade_no');
        if ($trade_status === 'TRADE_SUCCESS') {// 支付宝支付
            $Order = M("order");
            $arr['pay_status'] = '10';
            $arr['pay_time'] = time();
            $arr['pay_type'] = "支付宝";
            $arr['alipay_no'] = $trade_no;
            $Order->where('order_sn='.$out_trade_no)->save($arr);
            $a=$Order->where('order_sn='.$out_trade_no)->find();
            //var_dump(UID);exit;
            if ($a['type']==2){
                $User = M("ucenter_member");
                $arr['level'] = '1';
                $User->where('id='.$a['user_id'])->save($arr);
            }
            $this->success('支付成功',U('Order/pay_confirm',array('id'=>$a['id'])));
        }  else {
            // 其它类型的通知
            $this->error('失败，非支付宝支付',U('Order/pay_confirm'));
        }
    }
    /**
     * 支付完成后确认
     */
    public function pay_confirm()
    {
        $this->display();
    }

    public function wxPay()
    {
        $open_id = I("open_id");

        //订单号
        $orderNo = I('sn');
        $orderInfo = M("order")->where('order_sn='.$orderNo)->find();
        $orderFee = $orderInfo['active_price']*100; //传给微信时以分为单位
        $body = '优才圈商城';

        $wechatSubmit = new WechatSubmit();
        $wxReturn = $wechatSubmit->unifiedOrder($orderNo, $orderFee, $body, $open_id, "WEB");

        if (!$wxReturn || $wxReturn['return_code'] == 'FAIL') {
            $result = ["code" => 0, "msg" => "微信支付接口调用错误!".$wxReturn['return_msg']];
        } elseif ($wxReturn['result_code'] === 'FAIL') {
            $result = ["code" => 0, "msg" => $wxReturn['err_code_des']];
        } else {
            //生成页面调用参数
            $jsApiObj["appId"] = $wxReturn['appid'];
            $jsApiObj["timeStamp"] = (string)time();
            $jsApiObj["nonceStr"] = $wechatSubmit->createNoncestr();
            $jsApiObj["package"] = "prepay_id=" . $wxReturn['prepay_id'];
            $jsApiObj["signType"] = "MD5";
            $jsApiObj["paySign"] = $wechatSubmit->MakeSign($jsApiObj);

            $result = ["code" => 1, "msg" => "订单提交成功!", "data" => $jsApiObj];
        }
        $this->ajaxReturn($result);
    }

    /**
     * 微信异步回调
     */
    public function wxPayOrder()
    {
        $wechatSubmit = new WechatSubmit();
        $data = $wechatSubmit->parseNotify(I(''));

        $out_trade_no = $data['out_trade_no']; //订单号
        $transaction_id = $data['transaction_id']; //微信支付订单号
        if ($data["return_code"] === "SUCCESS") {
            $Order = M("order");
            $save_data = [
                "pay_status" => "10",
                "pay_time" => strtotime($data["time_end"]),
                "pay_type" => "微信",
                "alipay_no" => $transaction_id,
            ];

            $Order->where('order_sn='.$out_trade_no)->save($save_data);
            $order_info = $Order->where('order_sn='.$out_trade_no)->find();
            if ($order_info['type']==2){
                $User = M("ucenter_member");
                $arr['level'] = '1';
                $User->where('id='.$order_info['user_id'])->save($arr);
            }

            $return = ["return_code" => "SUCCESS", "return_msg" => ""];
        } else {
            $return = ["return_code" => "FAIL", "return_msg" => ""];
        }

        echo $wechatSubmit->ToXml($return);
    }

    public function wxPayConfirm()
    {
        $transaction_id = I("transaction_id");
        $wechatSubmit = new WechatSubmit();
        $queryResult = $wechatSubmit->orderQuery($transaction_id);

        if (!empty($queryResult)) {
            if ($queryResult["result_code"] === "SUCCESS" && $queryResult["trade_state"] === "SUCCESS") {
                $Order = M("order");
                $arr['pay_status'] = '10';
                $arr['pay_time'] = strtotime($queryResult["time_end"]);
                $arr['pay_type'] = "微信";
                $arr['alipay_no'] = $transaction_id;
                $Order->where('order_sn='.$queryResult["out_trade_no"])->save($arr);
                $a=$Order->where('order_sn='.$queryResult["out_trade_no"])->find();
                //var_dump(UID);exit;
                if ($a['type']==2){
                    $User = M("ucenter_member");
                    $arr['level'] = '1';
                    $User->where('id='.$a['user_id'])->save($arr);
                }

                $this->success('支付成功',U('Order/pay_confirm',array('id'=>$a['id'])));
            } else {
                $this->error($queryResult["trade_state_desc"]);
            }
        }
    }


    public function vip(){
        $id=I('id');
//        $open_id = $this->getopenid();

        $where['id'] = $id;
        $User=M('order');
        $order=$User->where($where)->find();

        $pid=$order['active_id'];
//        var_dump($pid);
        $msg['id'] = $pid;
        $User=M('active');
        $active=$User->where($msg)->find();
        $this->assign('active',$active);
        $this->assign('open_id',$open_id);

        $this->assign('order',$order);
        $this->display();
    }




    public function order_details(){
        $id=I('id');

        $where['id'] = $id;
        $User=M('order');
        $order=$User->where($where)->select();

        $where['id'] =$order[0]['active_id'];
        $User=M('active');
        $active=$User->where($where)->select();


        $this->assign('order',$order);
        $this->assign('active',$active);
        $this->display();
    }

    /**
     *
     * 收藏
     */
    public function collection()
    {
        if(IS_AJAX){

            $id=I('pid');
            $where['active_id'] = $id;
            $where['user_id'] = UID;

            $User=M('collection');
            $active=$User->where($where)->select();

            if($active){
                $del=$User->where($where)->delete();
                if($del){
                    $result=array('code'=>200,'msg'=>'取消成功','status'=>'0');
                }else{
                    $result=array('code'=>500,'msg'=>'取消失败');
                }

            }else{
                $data['user_id'] =UID;
                $data['active_id'] = $id;
                $data['create_time'] =time();
                $v=$User->add($data);
                if($v){
                    $result=array('code'=>200,'msg'=>'添加成功','status'=>'1');
                }else{
                    $result=array('code'=>500,'msg'=>'添加失败');
                }
            }
            $this->ajaxReturn($result);
        }
    }

    /**
     *
     * 创建订单
     */
    public function create_goods_order(){
       if(IS_POST){
            $pid=I('pid');
            $name=I('name');
            $phone=I('phone');
            $where['id'] = $pid;
            $User=M('active');
            $active=$User->where($where)->order('create_time')->select();
            if($name===''&&$phone===''){
               return;
            }else{
                $data['user_id']=UID;                   //用户ID。
                $data['active_id']=$pid;                //活动ID。
                $data['active_name']=I('active_name');  //活动名字。
                $data['active_price']=I('active_price');//订单价格。
                $data['ticket_name']=$name;             //报名人姓名。
                $data['ticket_phone']=$phone;           //报名人手机。
                $data['add_time']=time();               //订单添加时间。
                $data['order_sn']=time();               //订单号
                $data['active_img']=I('active_img');    //订单活动图片。
                $data['type']='1';                      //订单类型：普通订单。
                $Model = M('order');
                $insertid = $Model->add($data);
            }  

            $url=U('Order/vip',array('id'=>$insertid,'pid'=>$pid));
            $result=array('code'=>200,'msg'=>'订单提交成功','url'=>$url,'pid'=>$pid);
            $this->ajaxReturn($result);
        }
    }
    public function create(){
        $a=M('order')->where(array('user_id'=>session('user_auth')['uid'],'type'=>'2','pay_status'=>'10'))->find();
        if($a){
            $this->error('您已经是初级会员，无需再次升级。',U('User/index'));
        }
        $result = M('order')->where(array('user_id'=>session('user_auth')['uid'],'type'=>'2'))->find();
        if($result){ 
            $this->redirect("Order/vip",array('id'=>$result['id']));
        }
        $data['order_sn'] = time();
        $data['active_id'] = I('active_id','0');
        $data['active_name'] = I('active_name','会员升级');      
        $data['pay_status'] = '0';
        $data['add_time'] =  time(); 
        $data['active_price'] =  '36.5';
        $data['type'] =  '2';
        $data['active_img'] =  '/Public/Home/images/vip.png';
        $data['user_id'] = session('user_auth')['uid'];
        $order_id=M('order')->add($data); 
        if($order_id>0){
            $this->redirect("Order/vip",array('id'=>$order_id)); 
        }
    }

    public function update_status(){
        $data['status'] = '0';
        $id= I('id');
        $result = M('order')->where(array('id'=>$id))->save($data);
        
    }
    //新增订单
    public function addOrder()
    { 
        $data['card'] = I('card_no');
        $data['total'] = I('paygoods');
        $data['openid']  = I('openid');
        $order_id=D('order')->addOrderOne($data); 
        
        //统一下单接口 
        $t =array();
        $t['appid'] = $this->appid;
        $t['mch_id'] = $this->mch_id;  
        $t['nonce_str'] = rand(100,900).time();
        $t['body'] = "在线充值";
        $t['out_trade_no'] = $order_id;
        $t['total_fee'] = I('paygoods')*100;
        $t['spbill_create_ip'] = get_client_ip();
        $t['notify_url'] = "http://www.fzjtgps.com/phpinfo.php";
        $t['trade_type'] = "JSAPI";
        $t['openid'] = I('openid');
        ksort($t);
        $stringA = $this->ToUrlParams($t)."&key=".$this->key; 
        $t['sign'] = strtoupper(md5($stringA));
        $url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; 
        $tt = $this->ToXml($t);
        $ot =  $this->httppost($url,$tt,'POST'); 
        $ob = (array)simplexml_load_string($ot, 'SimpleXMLElement', LIBXML_NOCDATA); 
        if($order_id)
        { 
            $arr = array();  
            $arr['appId'] = $this->appid;
            $arr['timeStamp'] = (string)time();
            $arr['nonceStr'] = rand(100000,900000).time();
            $arr['package'] = "prepay_id=".$ob['prepay_id'];
            $arr['signType'] = "MD5"; 
            ksort($arr);
            $stringB = $this->ToUrlParams($arr)."&key=".$this->key; 
            $arr['paySign'] = strtoupper(md5($stringB)); 
            $result=array('code'=>200,'msg'=>'订单提交成功','data'=>json_encode($arr));
        }
        else
            $result=array('code'=>413,'msg'=>'订单提交失败');
        $this->ajaxReturn($result);
    } 
    public function ToXml($data)
    {
        if(!is_array($data) 
            || count($data) <= 0)
        {
            throw new WxPayException("数组数据异常！");
        } 
        $xml = "<xml>";
        foreach ($data as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml; 
    }
        /**
     * 以post方式提交xml到对应的接口url
     * 
     * @param string $xml  需要post的xml数据
     * @param string $url  url
     * @param bool $useCert 是否需要证书，默认不需要
     * @param int $second   url执行超时时间，默认30s
     * @throws WxPayException
     */
       //curl 请求 
    public function httppost($url,  $data = '', $method = 'GET', $json=false){
        $opts = array(
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            // CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'],
            // CURLOPT_FOLLOWLOCATION => 1,
            // CURLOPT_AUTOREFERER => 1,
            // CURLOPT_HEADER => 0,
        ); 
        /* 根据请求类型设置特定参数 */
        $opts[CURLOPT_URL] = $url;     // http_build_query会对特殊字符进行转义
       
        if(strtoupper($method) == 'POST'){
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $data;

            if($json){ //发送JSON数据
                $opts[CURLOPT_HTTPHEADER] = array(
                    'Content-Type: application/json; charset=UTF-8',  
                    'Content-Length: ' . strlen($data),
                );
            }
        }
        // var_dump($opts);
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data  = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch); 
        //发生错误，抛出异常
        if($error) throw new \Exception('请求发生错误：' . $error);
        // FPC($data);
        return  $data;
    }
//    public function GetOpenid()
//    {
//        //通过code获得openid
//        if (!isset($_GET['code'])){
//            //触发微信返回code码
//            $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
////            var_dump($baseUrl);exit;
//            $url = $this->__CreateOauthUrlForCode($baseUrl);
//            Header("Location: $url");
//            exit();
//        } else {
//            //获取code码，以获取openid
//            $code = $_GET['code'];
//            $openid = $this->GetOpenidFromMp($code);
//            return $openid;
//        }
//    }
//    public function __CreateOauthUrlForCode($redirectUrl)
//    {
//        $urlObj["appid"] = $this->appid;
//        $urlObj["redirect_uri"] = "$redirectUrl";
//        $urlObj["response_type"] = "code";
//        $urlObj["scope"] = "snsapi_base";
//        $urlObj["state"] = "STATE"."#wechat_redirect";
//        $bizString = $this->ToUrlParams($urlObj);
//
//        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
//    }
//    public function GetOpenidFromMp($code)
//    {
//        $url = $this->__CreateOauthUrlForOpenid($code);
//        //初始化curl
//        $ch = curl_init();
//        //设置超时
//        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
//        curl_setopt($ch, CURLOPT_HEADER, FALSE);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//        // if(WxPayConfig::CURL_PROXY_HOST != "0.0.0.0"
//        //     && WxPayConfig::CURL_PROXY_PORT != 0){
//        //     curl_setopt($ch,CURLOPT_PROXY, WxPayConfig::CURL_PROXY_HOST);
//        //     curl_setopt($ch,CURLOPT_PROXYPORT, WxPayConfig::CURL_PROXY_PORT);
//        // }
//        //运行curl，结果以jason形式返回
//        $res = curl_exec($ch);
//        curl_close($ch);
//        //取出openid
//        $data = json_decode($res,true);
//        $this->data = $data;
//        $openid = $data['openid'];
//        return $openid;
//    }
//    private function __CreateOauthUrlForOpenid($code)
//    {
//        $urlObj["appid"] = $this->appid;
//        $urlObj["secret"] = $this->secret;
//        $urlObj["code"] = $code;
//        $urlObj["grant_type"] = "authorization_code";
//        $bizString = $this->ToUrlParams($urlObj);
//        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
//    }
//    private function ToUrlParams($urlObj)
//    {
//        $buff = "";
//        foreach ($urlObj as $k => $v)
//        {
//            if($k != "sign"){
//                $buff .= $k . "=" . $v . "&";
//            }
//        }
//        $buff = trim($buff, "&");
//        return $buff;
//    }
    //支付页
    public function pay()
    {
        $orderId = I('order_id');
        $where = array();
        $where['id'] = $orderId;
        $order = M('order')->where($where)->find();
        $this->assign('order',$order);
        FPC($order);
        $this->display();
    }
}